package pun.potato;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pun.potato.BubbleAdapter.ViewHolder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;




public class PlayScreen extends ListActivity {

	ArrayList<Pun> messages;
	ArrayList<Integer> yourUpvoted = new ArrayList<Integer>();
	ArrayList<Integer> theirUpvoted = new ArrayList<Integer>();
	BubbleAdapter adapter;
	final static int TIMEOUT_TIME = 15000; //15 seconds

	Timer timer;
	Dialog partnerDialog; 
	int dialogTime;
	int punTime;
	String topic = "RESOVOIRS";

	int pun_id = 0;
	int new_pun_id;
	int userid;
	String username;
	int partnerId;
	String partnerName;
	int threadId;
	int difficulty;
	int playerMojo;
	int partnerMojo;

	public static boolean yourTurn;
	boolean stillLooking;
	boolean sackedAPlayer = false;
	boolean checkPartner;
	boolean upvoteGiven = false;
	int upvotePun = -1;
	int sack = 0;
	//maxes out at 3
	int thread_score = 3;
	AsyncTask<String, String, String> checkTurn;
	AsyncTask<String, String, String> sackPlayer;

	MyTimer myTimer;
	TimeoutTimer timeouttimer;
	ProgressDialog pDialog;

	public static int x;
	public static int y;
	boolean resetPunt = false;
	boolean showPunt = false;
	boolean quit = false;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playscreen);

		Display display = getWindowManager().getDefaultDisplay();
		//Point size = new Point();
		x = display.getWidth();  // deprecated
		y = display.getHeight(); 

		messages = new ArrayList<Pun>();

		//messages.add(new Pun("Hello", userid));
		//messages.add(new Pun("Hi!", userid));

		adapter = new BubbleAdapter(getApplicationContext(), messages);
		setListAdapter(adapter);


		//get the activity params
		getActivityParams();

		//create the initial dialog
		dialogTime = 10000;
		partnerDialog = createPartnerTopicDialog();
		partnerDialog.setCancelable(false);
		partnerDialog.show();

		//dismiss the inital dialog after its out of time
		TimerTask task = new TimerTask(){
			public void run(){
				partnerDialog.dismiss();      		
			}
		};        
		Timer internalTimer = new Timer();
		internalTimer.schedule(task, dialogTime);

		//set the topic, username, and opponent name 

		TextView topicPlay = (TextView)findViewById(R.id.topic);
		Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/hotdog.ttf");
		topicPlay.setTypeface(tf);
		TextView usernameDisplay = (TextView)findViewById(R.id.playername);
		TextView opponentName = (TextView)findViewById(R.id.opponentname);
		TextView mojo1 = (TextView)findViewById(R.id.playerpoints);
		TextView mojo2 = (TextView)findViewById(R.id.enemypoints);
		topicPlay.setText(topic);
		usernameDisplay.setText(username);
		opponentName.setText(partnerName);
		//Log.d("player Mojo", Integer.toString(playerMojo)); 
		mojo1.setText(Integer.toString(playerMojo));
		mojo2.setText(Integer.toString(partnerMojo)); 

		//by default your turn... otherwise it resets
		ImageView panda = (ImageView)findViewById(R.id.playersTurn);
		panda.setVisibility(View.VISIBLE);
		ImageView evil_panda = (ImageView)findViewById(R.id.enemysTurn);
		evil_panda.setVisibility(View.INVISIBLE);


		startTimer();
		stillLooking = true;
		yourTurn = false;

		checkTurn = new CheckTurn();
		checkTurn.execute("start");




		Button sendButton = (Button)findViewById(R.id.send);
		sendButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				//allows player to send message
				if(!myTimer.getDead()){
					if(yourTurn){				
						checkPartner = false;
						new SendMessage().execute("start");

					}
					else{
						Toast.makeText(getApplicationContext(), "Wait your turn!", Toast.LENGTH_LONG).show();
					}
				}
			}

		});

		ImageButton sackButton = (ImageButton)findViewById(R.id.sackButton);
		sackButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				if(!myTimer.getDead()){
					if(!yourTurn){
						sackedAPlayer = true;
						stillLooking = false;
						sackPlayer = new SackAPlayer();
						sackPlayer.execute("start");
					}
					else{
						Toast.makeText(getApplicationContext(), "Your partner did his job, now do yours! You can't sack a player when it is your turn.", Toast.LENGTH_LONG).show();
					}
				}
			}

		});


	}

	private void startTimer(){

		//start the timer for the pun

		int totalSeconds = (int)(punTime / 1000);
		int minutes = totalSeconds / 60;
		int seconds = totalSeconds % 60; 
		TextView timerTextView = (TextView)findViewById(R.id.time);
		if(difficulty == 1){
			//1800
			punTime = 60000;
		} else if(difficulty == 2){
			punTime = 90000;
		} else {
			punTime = 60000;
		}
		myTimer = new MyTimer(punTime, 1000);
		myTimer.setTextView(timerTextView, this);
		if(seconds < 10){
			timerTextView.setText(minutes + ":0" + seconds);
		}
		else{
			timerTextView.setText(minutes + ":" + seconds);
		}
		partnerDialog.setOnDismissListener(new OnDismissListener(){

			@Override
			public void onDismiss(DialogInterface dialog) {
				myTimer.start();
			}

		});

	}

	private void resetTimer(int time){

		myTimer.cancel();
		int totalSeconds = (int)(time / 1000);
		int minutes = totalSeconds / 60;
		int seconds = totalSeconds % 60;
		TextView timerTextView = (TextView)findViewById(R.id.time);
		myTimer = new MyTimer(time, 1000);
		myTimer.setTextView(timerTextView, this);
		if(seconds < 10){
			timerTextView.setText(minutes + ":0" + seconds);
		}
		else{
			timerTextView.setText(minutes + ":" + seconds);
		}   
		myTimer.start();

	}

	public void endGame(){

		if(!yourTurn){
			//this will end the activity by calling ResetPid()
			//you've won the game!
			TimerTask task = new TimerTask(){
				public void run(){
					yourTurn = true;
					stillLooking = false;     		
				}
			};
			Timer internalTimer = new Timer();
			internalTimer.schedule(task, 5000);

		}
		else{
			//simply end the activity
			//this is executed when someone loses the game
			Intent returnData = new Intent();
			returnData.putExtra("returnValue", 3);
			setResult(Activity.RESULT_OK, returnData);
			PlayScreen.this.finish();
		}
	}


	@Override
	public void onBackPressed() {
		//resets the players pid, pname, and the partner's corresponding data
		//add dialog here to check if you want to quit

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to quit?");
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				quit = true;
				//this happens if you want to end the game
				if(yourTurn){
					checkPartner = false;
					sack = 1;
					new ResetPidPname().execute("start");
				}
				else{
					yourTurn = true;
					stillLooking = false;
				}

			}
		});

		builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();

			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	public boolean containsPun(int id){
		for(int i=0;i<messages.size();i++){
			int temp = messages.get(i).pun_id;
			if(temp == id){
				return true;
			}
		}
		return false;
	}

	private void parsePreviousMessages(Bundle e){
		ArrayList<String> sendIds = e.getStringArrayList("sendIds");
		ArrayList<String> conversation = e.getStringArrayList("conversation");
		ArrayList<String> names = e.getStringArrayList("names");
		ArrayList<Integer> pun_ids = e.getIntegerArrayList("pun_ids");
		//Log.d("past conversation", "Number of prev messages: "+sendIds.size());
		//for some reason it isn't entering here anymore even when I have entered a previous message...
		for(int i = 0; i < sendIds.size(); i++){
			//LinearLayout layout = (LinearLayout)findViewById(R.id.linearlayout);
			//LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			//TextView tv = new TextView(getApplicationContext());
			//tv.setText(sendIds.get(i) + " " + names.get(i) + ": " + conversation.get(i));
			if(!containsPun(pun_ids.get(i))){
				addNewMessage(new Pun(conversation.get(i), Integer.parseInt(sendIds.get(i)), names.get(i), pun_ids.get(i)));
				//Log.d("past conversation", conversation.get(i));
			}
			//tv.setGravity(Gravity.LEFT);
			//tv.setLayoutParams(lparams);
			//layout.addView(tv);
		}
	}




	private void getActivityParams(){
		Bundle e = getIntent().getExtras();
		if (e != null) {
			userid = e.getInt("userid");
			username = e.getString("username");
			partnerId = e.getInt("partnerId");
			partnerName = e.getString("partnerName");
			playerMojo = e.getInt("playerMojo");
			partnerMojo = e.getInt("partnerMojo");
			topic = e.getString("topic");
			threadId = e.getInt("thread_id");
			difficulty = e.getInt("difficulty");
			parsePreviousMessages(e);
			//Log.d("playScreen", "userid: " + userid + " username: " + username + " partnerId: " + partnerId + " partnerName: " + partnerName);
		}
	}

	private Dialog createPartnerTopicDialog(){

		//replace with partner/topic layout
		final View partnerTopicDialog = View.inflate(this, R.layout.partnertopicdialog, null);
		TextView topicDialog = (TextView)partnerTopicDialog.findViewById(R.id.TextView02);
		TextView partnerDialog = (TextView)partnerTopicDialog.findViewById(R.id.textview2);
//		TextView username = (TextView)partnerTopicDialog.findViewById(R.id.textView1);
//		TextView topicIs = (TextView)partnerTopicDialog.findViewById(R.id.TextView01);
//		TextView getReady = (TextView)partnerTopicDialog.findViewById(R.id.textView3);
		topicDialog.setText(topic);
		partnerDialog.setText(partnerName);
		Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Ranger.ttf");
		topicDialog.setTypeface(tf);
		partnerDialog.setTypeface(tf);
//		username.setTypeface(tf);
//		topicIs.setTypeface(tf);
//		getReady.setTypeface(tf);

		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(0);


		builder.setView(partnerTopicDialog);

		return builder.create();
	}


	class SendMessage extends AsyncTask<String, String, String>{


		EditText messageBox = (EditText)findViewById(R.id.text);
		String message;
		boolean sendMessageSuccess;
		boolean invalidCharacters = false;
		boolean emptyMessage = true;

		@Override
		protected String doInBackground(String... arg0) {

			message = messageBox.getText().toString();

			if(!message.equals("")){
				emptyMessage = false;
				if(!message.contains("#") && !message.contains("%")&& !message.contains("&") && !message.contains("+") && !message.contains("\"") && !message.contains("`") && !message.contains("|") && !message.contains("{") && !message.contains("}") && !message.contains("\t") && !message.contains("^") && !message.contains("\\") && !message.contains("<") && !message.contains(">") && !message.contains("\n")){ //invalid characters
					String messageToSend = message.replace(" ", "%20");
					messageToSend = messageToSend.replace("'", "\'");
					String nameToSend = username.replace(" ", "%20");
					HttpClient client = new DefaultHttpClient();
					HttpPost httpPost = new HttpPost(Preferences.GetURL() + "sendMessage.php?sid=" + userid + "&rid=" + partnerId + "&thread_id=" + threadId + "&content=" + messageToSend + "&name=" + nameToSend + Preferences.GetLiveServerPreferences());

					try{
						HttpResponse response = client.execute(httpPost);
						String jsonString = EntityUtils.toString(response.getEntity());
						//Log.d("sendMessage", jsonString);

						if(jsonString.equals("0")){
							sendMessageSuccess = false;
						}
						else{
							sendMessageSuccess = true;
							pun_id = Integer.parseInt(jsonString);
						}

					}catch(ClientProtocolException e){
						//Log.e("sendMessage", "ClientProtocolException");
					}catch(IOException e){
						//Log.e("sendMessage", "IOException");
					}
				}
				else{
					sendMessageSuccess = false;
					invalidCharacters = true;
				}

			}
			else{
				sendMessageSuccess = false;
				emptyMessage = true;
			}


			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(sendMessageSuccess){
				messageBox.setText("");
				messageBox.clearFocus(); //this might not work
				yourTurn = false;
				//update the client 
				Pun p = new Pun(message, userid, username, pun_id);
				p.setIsMine(true);
				addNewMessage(p);


				//LinearLayout layout = (LinearLayout)findViewById(R.id.linearlayout);
				//LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				//TextView tv = new TextView(getApplicationContext());
				//tv.setText(username + ": " + message);
				//tv.setGravity(Gravity.LEFT);
				//tv.setLayoutParams(lparams);
				//layout.addView(tv); 
				resetTimer(punTime);
				checkTurn = new CheckTurn();
				checkTurn.execute("start");
				
				if(showPunt){
					ImageButton b = (ImageButton)findViewById(R.id.sackButton);
					b.setVisibility(View.VISIBLE);
					Button b2 = (Button)findViewById(R.id.send);
					b2.setVisibility(View.INVISIBLE);
				}
			}
			else{
				if(emptyMessage){
					Toast.makeText(getApplicationContext(), "What? You can't submit a pun without typing anything!", Toast.LENGTH_LONG).show();
				}
				else{
					if(invalidCharacters){
						Toast.makeText(getApplicationContext(), "Sorry, your pun contains an invalid character.", Toast.LENGTH_LONG).show();
					}
					else{
						Toast.makeText(getApplicationContext(), "Something went wrong when sending your pun", Toast.LENGTH_LONG).show();
					}
				}
			}

		}
	}

	class CheckTurn extends AsyncTask<String, String, String>{

		String mostRecentPun;
		boolean upload = false;
		boolean opponentQuit = false;
		int uploaded;

		@Override
		protected String doInBackground(String... params) {
			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Preferences.GetURL() + "checkTurn.php?thread_id=" + threadId + "&rid=" + userid + "&pid=" + partnerId + "&upvotePun="+upvotePun + Preferences.GetLiveServerPreferences());

			try{
				while(!yourTurn){
					//Log.d("Holder pun id", "checkTurn: "+upvotePun);
					//long i = getListView().getSelectedItemId();

					if(!stillLooking){ 
						break; 
					}
					HttpResponse response = client.execute(httpPost);
					String jsonString = EntityUtils.toString(response.getEntity());
					//update mojo's

					//Log.d("checkTurn", jsonString);
					JSONObject object = new JSONObject(jsonString); 



					if(object.getInt("turn") == 1){
						//it is your turn
						yourTurn = true;
						mostRecentPun = object.getString("content");

						new_pun_id = object.getInt("pun_id");
						uploaded = object.getInt("uploaded");

						//Log.d("checkTurn", mostRecentPun);
					}
					else if(object.getInt("turn") == -1){
						//this means the other play quit
						stillLooking = false;
						opponentQuit = true;
					}
					else{
						yourTurn = false;
					}

					if(upvoteGiven == true){
						partnerMojo = object.getInt("pmojo");
						playerMojo = object.getInt("mojo");
						upvoteGiven = false;
					}

					publishProgress();
					JSONArray m = object.getJSONArray("messages");

					if(m != null){
						for(int i = 0; i < m.length(); i++){
							JSONObject mess = m.getJSONObject(i);
							//int upvoted = mess.getInt("upvoted");
							int p = mess.getInt("pun_id");
							if(mess.getInt("upvoted") != 0){ 
								for(int j=0; j < messages.size(); j++){
									//Log.d("messageJSON", "Inside messages for loop");
									if(messages.get(j).pun_id == p){
										messages.get(j).upvoted = true;
										upvoteGiven = true;
									}
								}
							}
						}
					}

				}


			}catch(ClientProtocolException e){
				//e.printStackTrace();
				//Log.e("checkTurn", "ClientProtocolException");
			}catch(IOException e){
				//e.printStackTrace();
				//Log.e("checkTurn", "IOException");
			}catch(JSONException e){
				//e.printStackTrace();
				//Log.e("checkTurn", "JSONException");
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			if(stillLooking){

				//changed this from checking the string "null"
				try{
					if(!mostRecentPun.equals("null")){

						addNewMessage(new Pun(mostRecentPun, partnerId, partnerName, new_pun_id));
						resetTimer(punTime);

						ImageButton b = (ImageButton)findViewById(R.id.sackButton);
						b.setVisibility(View.INVISIBLE);
						Button b2 = (Button)findViewById(R.id.send);
						b2.setVisibility(View.VISIBLE);
						showPunt = true;



						if(uploaded == 1){
							if(!upload){
								//Toast.makeText(getApplicationContext(), "Your conversation has been uploaded!", Toast.LENGTH_LONG).show();
								upload = true;
							}
						}
					}
					checkPartner = true;
					new CheckPartnerStatus().execute("start");
				}catch(NullPointerException e){
					//Toast.makeText(getApplicationContext(), "Bug happened", Toast.LENGTH_LONG).show();
					yourTurn = false;
					checkTurn = new CheckTurn();
					checkTurn.execute("start");
				}
			}
			else{
				if(opponentQuit){
					//perhaps add some dialog here to tell the user that their partner quit
					yourTurn = false;
					//this is executed when your opponent quit
					Intent returnData = new Intent();
					returnData.putExtra("returnValue", 1);
					setResult(Activity.RESULT_OK, returnData);
					PlayScreen.this.finish();
				}
				else if(sackedAPlayer){
					//Log.d("CheckTurn", "You just sacked a player");
				}
				else{
					//this will reset the database and quit out of the activity when it isnt your turn
					sack = 1;
					new ResetPidPname().execute("start");
				}

			}

		}

		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);

			TextView mojo1 = (TextView)findViewById(R.id.playerpoints);
			TextView mojo2 = (TextView)findViewById(R.id.enemypoints);

			//make it flashy
			//if(mojo1.getText().equals(Integer.toString(playerMojo)))

			mojo1.setText(Integer.toString(playerMojo));
			mojo2.setText(Integer.toString(partnerMojo));

			if(yourTurn){
				ImageView panda = (ImageView)findViewById(R.id.playersTurn);
				panda.setVisibility(View.VISIBLE);
				ImageView evil_panda = (ImageView)findViewById(R.id.enemysTurn);
				evil_panda.setVisibility(View.INVISIBLE);
			} else {
				ImageView panda = (ImageView)findViewById(R.id.playersTurn);
				panda.setVisibility(View.INVISIBLE);
				ImageView evil_panda = (ImageView)findViewById(R.id.enemysTurn);
				evil_panda.setVisibility(View.VISIBLE);
			}

			adapter.notifyDataSetChanged();
			/*		
    		for(int i=0; i < messages.size(); i++){
            	View v = getListView().getChildAt(i);
            	ViewHolder holder = (ViewHolder) v.getTag();
    			Pun p = messages.get(i);
    			if(p.upvoted){
    				if(p.sid == userid){
    					holder.icon.setImageResource(R.drawable.nice_panda_gold);
    					holder.icon.setTag(R.drawable.nice_panda_gold);
    				} else {
    					holder.icon.setImageResource(R.drawable.evil_panda_gold);
    					holder.icon.setTag(R.drawable.evil_panda_gold);
    				}
    			}
    		}*/
			/*
    		int c = getListView().getChildCount();
            for(int i=0; i < c; i++){
            	View v = getListView().getChildAt(i);
            	ViewHolder holder = (ViewHolder) v.getTag();

            		if(yourUpvoted.contains(holder.pun_id)){
            			Log.d("compare", "CheckTurn: "+holder.pun_id);
            			holder.icon.setImageResource(R.drawable.nice_panda_gold);
            			holder.icon.setTag(R.drawable.nice_panda_gold);
            		}

            		if(theirUpvoted.contains(holder.pun_id)){
            			Log.d("compare", "CheckTurn: "+holder.pun_id);
            			holder.icon.setImageResource(R.drawable.evil_panda_gold);
            			holder.icon.setTag(R.drawable.evil_panda_gold);
            		}

            }*/
			//upvotePun = -1;

			//if(titleTextBox!=null)
			//    titleTextBox.setText(updating +" "+ values[0] + "...");
			//if (Build.VERSION.SDK_INT>=11) {
			//    ActionBar ab = getActionBar();
			//    if (ab!=null)
			//        ab.setSubtitle(updating +" "+ values[0] + "...");
			//}

			//}
		}

	}


	class ResetPidPname extends AsyncTask<String, String, String>{

		int awardPoints;

		@Override
		protected String doInBackground(String... params) {
			int points = messages.size();
			awardPoints = 0;
			if(sack == 0){ } else {
				if(myTimer.getDead()){
					awardPoints = points;
				}
			}
			if(quit){
				//you lose 5 points when you quit
				awardPoints = -5;
			}
			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Preferences.GetURL() + "resetPid.php?id=" + userid + "&pid=" + partnerId + "&dead=1" + "&thread_id=" + threadId + "&sacked=" + sack + "&awardPoints="+ awardPoints +Preferences.GetLiveServerPreferences());

			try{
				HttpResponse response = client.execute(httpPost);
				String jsonString = EntityUtils.toString(response.getEntity());
				//Log.d("resetPidPname", jsonString);
			}catch(ClientProtocolException e){
				//Log.e("resetPidPname", "ClientProtocolException");
			}catch(IOException e){
				//Log.e("resetPidPname", "IOException");
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			yourTurn = false;
			//this can be executed for a variety of reasons
			if(sack == 0){
				Intent returnData = new Intent();
				returnData.putExtra("returnValue", 2);
				setResult(Activity.RESULT_OK, returnData);
			}
			else{
				if(myTimer.getDead()){
					//player has won the game... therefore they should receive all the mojo points
					int points = messages.size();
					/* find a place to do this
					HttpClient client = new DefaultHttpClient();
					HttpPost httpPost = new HttpPost(Preferences.GetURL() + "updateMojo.php?id=" + userid+ "&mojo="+points+ Preferences.GetLiveServerPreferences());

					try{
							HttpResponse response = client.execute(httpPost);
							String jsonString = EntityUtils.toString(response.getEntity());
							JSONObject object = new JSONObject(jsonString); 
							playerMojo = object.getInt("mojo");
							Log.d("GOT HERE", ""+playerMojo);

					}catch(ClientProtocolException e){
						e.printStackTrace();
						Log.e("checkTurn", "ClientProtocolException");
					}catch(IOException e){
						e.printStackTrace();
						Log.e("checkTurn", "IOException");
					}catch(JSONException e){
						e.printStackTrace();
						Log.e("checkTurn", "JSONException");
					} */

					Intent returnData = new Intent();
					returnData.putExtra("returnValue", 4);
					returnData.putExtra("pointsAwarded", points);
					setResult(Activity.RESULT_OK, returnData);
				}
				else{
					Intent returnData = new Intent();
					returnData.putExtra("returnValue", 0);
					returnData.putExtra("pointsAwarded", awardPoints);
					setResult(Activity.RESULT_OK, returnData);
				}
			}	
			PlayScreen.this.finish();
		}

	}

	class CheckPartnerStatus extends AsyncTask<String, String, String>{

		int rPid = 0;
		int sacked = 1;

		@Override
		protected String doInBackground(String... params) {
			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Preferences.GetURL() + "checkPartnerStatus.php?id=" + userid + "&pid=" + partnerId + "&thread_id="+ threadId+ "&upvotePun="+ upvotePun + Preferences.GetLiveServerPreferences());

			try{
				while(checkPartner){
					//Log.d("Holder pun id", "checkPartnerStatus: "+upvotePun);
					HttpResponse response = client.execute(httpPost);
					String jsonString = EntityUtils.toString(response.getEntity());
					JSONObject object = new JSONObject(jsonString);
					rPid = object.getInt("turn");
					sacked = object.getInt("sacked");

					//if(upvotePun != -1){
					//	publishProgress();
					//}
					//if(upvotePartner == true){
					if(upvoteGiven){
						int yourMojo = object.getInt("pmojo");
						int myMojo = object.getInt("mojo");
						playerMojo = myMojo;
						partnerMojo = yourMojo;
						upvoteGiven = false;
					}

					publishProgress();

					JSONArray m = object.getJSONArray("messages");
					if(m != null){
						for(int i = 0; i < m.length(); i++){
							//Log.d("playerMojo", "messages returned: " + m.length());
							JSONObject mess = m.getJSONObject(i);
							//int upvoted = mess.getInt("upvoted");
							int p = mess.getInt("pun_id");
							if(mess.getInt("upvoted") != 0){
								for(int j=0; j < messages.size(); j++){
									if(messages.get(j).pun_id == p){
										messages.get(j).upvoted = true;
										//Log.d("newTest", "pun_id within messages"+ pun_id);
										upvoteGiven = true;
									}
								}


								/*	
								if(object.getInt("sid") == partnerId){
									if(!theirUpvoted.contains(p)){
										//upvotePun = -1;
										theirUpvoted.add(p); 
										Log.d("playerMojo", "theirUpvoted size: "+theirUpvoted.size());
										partnerMojo = yourMojo;
										publishProgress();
									}
								} else if(object.getInt("sid") == userid){
									if(!yourUpvoted.contains(p)){
										yourUpvoted.add(p);
										Log.d("playerMojo", "yourUpvoted size: "+yourUpvoted.size());
										playerMojo = myMojo;
										publishProgress();
									}
								}*/
							}
						}
					} 
					if(rPid == -1){
						yourTurn = false;
						checkPartner = false;						
						//this is executed when your partner quits
						Intent returnData = new Intent();
						returnData.putExtra("returnValue", 1);
						setResult(Activity.RESULT_OK, returnData);
						PlayScreen.this.finish();
					}
					if(sacked == 0){
						//you've been sacked!
						sack = 0;
						checkPartner = false;
						new ResetPidPname().execute("start");
					}

				}



			}catch(ClientProtocolException e){
				//e.printStackTrace();
				//Log.e("ClassPartnerStatus", "ClientProtocolException");
			}catch(IOException e){
				//e.printStackTrace();
				//Log.e("ClassPartnerStatus", "IOException");
			}catch(JSONException e){
				//e.printStackTrace();
				//Log.e("ClassPartnerStatus", "JSONException");
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);

			TextView mojo1 = (TextView)findViewById(R.id.playerpoints);
			TextView mojo2 = (TextView)findViewById(R.id.enemypoints);
			mojo1.setText(Integer.toString(playerMojo));
			mojo2.setText(Integer.toString(partnerMojo));

			adapter.notifyDataSetChanged();
			/*	
    		for(int i=0; i < messages.size(); i++){
            	View v = getListView().getChildAt(i);
            	ViewHolder holder = (ViewHolder) v.getTag();
    			Pun p = messages.get(i);
    			if(p.upvoted){
    				if(p.sid == userid){
    					holder.icon.setImageResource(R.drawable.nice_panda_gold);
    					holder.icon.setTag(R.drawable.nice_panda_gold);
    				} else {
    					holder.icon.setImageResource(R.drawable.evil_panda_gold);
    					holder.icon.setTag(R.drawable.evil_panda_gold);
    				}
    			}
    		}*/
			/*       
            int c = getListView().getChildCount();
            for(int i=0; i < c; i++){
            	View v = getListView().getChildAt(i);
            	ViewHolder holder = (ViewHolder) v.getTag();

            	if(yourUpvoted.contains(holder.pun_id)){
            		Log.d("compare", "CheckPartnerStatus"+ holder.pun_id);
            		holder.icon.setImageResource(R.drawable.nice_panda_gold);
            		holder.icon.setTag(R.drawable.nice_panda_gold);
            	}
            	if(theirUpvoted.contains(holder.pun_id)){
            		Log.d("compare", "CheckPartnerStatus"+ holder.pun_id);
            		holder.icon.setImageResource(R.drawable.evil_panda_gold);
            		holder.icon.setTag(R.drawable.evil_panda_gold);
            	}
            }
			 */
			//upvotePun = -1;

			//TextView mojo = (TextView)findViewById(R.id.playerpoints);
			//mojo1.setText(Integer.toString(playerMojo));
			//mojo.setText(Integer.toString(playerMojo));

			//if(titleTextBox!=null)
			//    titleTextBox.setText(updating +" "+ values[0] + "...");
			//if (Build.VERSION.SDK_INT>=11) {
			//    ActionBar ab = getActionBar();
			//    if (ab!=null)
			//        ab.setSubtitle(updating +" "+ values[0] + "...");
			//}

		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			//ImageButton b = (ImageButton)findViewById(R.id.sackButton);
			//b.setVisibility(View.VISIBLE);
			//Button b2 = (Button)findViewById(R.id.send);
			//b2.setVisibility(View.INVISIBLE);

		}




	}

	class SackAPlayer extends AsyncTask<String, String, String>{

		int sacks = 0;
		String pname = "";
		int pid = -1;

		@Override
		protected void onPreExecute() {
			pDialog = ProgressDialog.show(PlayScreen.this, "", "Waiting for new player...", true);
			super.onPreExecute();
			timeouttimer = new TimeoutTimer(TIMEOUT_TIME, 1000);
			timeouttimer.start();
		}

		@Override
		protected String doInBackground(String... arg0) {

			String nameToSend = username.replace(" ", "%20");
			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Preferences.GetURL() + "sackPlayer.php?id=" + userid + "&pid=" + partnerId + "&thread_id=" + threadId + "&name=" + nameToSend + Preferences.GetLiveServerPreferences());
			//need to make it not crash when there are no more players online

			try{
				while(pid == -1){
					if(pid == -4){
						resetPunt = true;
					}
					if(pid == -2 || pid == -3 || resetPunt){
						//you have run out of sacks
						break;
					}
					HttpResponse response = client.execute(httpPost);
					String jsonString = EntityUtils.toString(response.getEntity());
					JSONObject object = new JSONObject(jsonString);
					pid = object.getInt("pid");
					pname = object.getString("pname"); 
				}
			}catch(ClientProtocolException e){
				//e.printStackTrace();
				//Log.e("SackAPlayer", "ClientProtocolException");
			}catch(IOException e){
				//e.printStackTrace();
				//Log.e("SackAPlayer", "IOException");
			}catch(JSONException e){
				//e.printStackTrace();
				//Log.e("SackAPlayer", "JSONException"); 
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			if(resetPunt){
				new ResetAfterTimeout().execute("start");
			}
			else{
				pDialog.dismiss();
				timeouttimer.cancel();
				if(pid == -2){
					Toast.makeText(getApplicationContext(), "The thread has run out of sacks.", Toast.LENGTH_LONG).show();
				}
				else if(pid == -3){
					Toast.makeText(getApplicationContext(), "Hey man, you've been punting a lot. Your booting privileges have been suspended until you stop being a dick.", Toast.LENGTH_LONG).show();
				}
				else if(pid == -4){
					//received a message
					Toast.makeText(getApplicationContext(), "Didn't find a player in time.", Toast.LENGTH_LONG).show();
					new ResetAfterTimeout().execute("start");
				}
				else{
					partnerId = pid;
					partnerName = pname;
					//update the client for partner name
					TextView opponent = (TextView)findViewById(R.id.opponentname);
					opponent.setText(pname);
					Toast.makeText(getApplicationContext(), "A new partner has been found!\nTheir name is " + pname + ".", Toast.LENGTH_LONG).show();
					resetTimer(punTime + 10000); //add 10 seconds here because the new partner will have a dialog that lasts 10 seconds long
				}
			}

			stillLooking = true; 
			sackedAPlayer = false;
			new CheckTurn().execute("start");
			//make sure that the timing is correct on both phones
			super.onPostExecute(result);
		}

	}

	class TimeoutTimer extends CountDownTimer{

		int minutes;
		int seconds;

		public TimeoutTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
			int totalSeconds = (int)(millisInFuture / 1000);
			minutes = totalSeconds / 60;
			seconds = totalSeconds % 60;
			resetPunt = false;
		}



		@Override
		public void onFinish() {
			pDialog.dismiss();
			resetPunt = true;
			Toast.makeText(getApplicationContext(), "Punting failed!", Toast.LENGTH_LONG).show();
		}

		@Override
		public void onTick(long millisUntilFinished) {
			//dont do anything
		}


	}

	class ResetAfterTimeout extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {

			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Preferences.GetURL() + "resetAfterTimeout.php?id=" + userid + Preferences.GetLiveServerPreferences());

			try{
				HttpResponse response = client.execute(httpPost);
				String jsonString = EntityUtils.toString(response.getEntity());
				//Log.d("ResetAfterTimeout", jsonString);
			}catch(IOException e){
				e.printStackTrace();
			}

			return null;
		}


	}

	void addNewMessage(Pun m)
	{
		messages.add(m);
		//set the upvoted of each pun
		/*
		for (int i=0; i < theirUpvoted.size();i++){
			int id = theirUpvoted.get(i);
			for(int j=0; j < messages.size(); j++){
				if(messages.get(j).pun_id == id){
					messages.get(j).setUpvoted(true);
				}
				Log.d("Pun id's in for loop", ""+ messages.get(j).getPunId());
			}
		}

		for (int i=0; i < yourUpvoted.size();i++){
			int id = yourUpvoted.get(i);
			for(int j=0; j < messages.size(); j++){
				if(messages.get(j).pun_id == id){
					messages.get(j).setUpvoted(true);
				}
				Log.d("Pun id's in for loop", ""+ messages.get(j).getPunId());
			}
		}
		 */
		adapter.notifyDataSetChanged();
		getListView().setSelection(messages.size()-1);
		//getListView().setOnClickListener(l)
		getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {  
			//bug is onclick doesn't get received for received puns
			@Override
			public void onItemClick(AdapterView<?> arg0, View v,
					int arg2, long arg3) {
				ViewHolder holder = (ViewHolder) v.getTag();
				Object o = holder.icon.getTag();
				if(Integer.parseInt(o.toString()) == R.drawable.evil_panda){
					//Log.d("Panda clicked", "PANDAS");
					holder.icon.setImageResource(R.drawable.evil_panda_gold);
					holder.icon.setTag(R.drawable.evil_panda_gold);
					holder.upvoted++;
					//increment the other player's mojo by one and turn the panda gold
					upvotePun = holder.pun_id;
					//Log.d("Holder pun id", "onClick: "+upvotePun);
					for(int i=0; i < messages.size();i++){
						if(messages.get(i).pun_id == holder.pun_id){
							messages.get(i).setUpvoted(true);
						}
					}
				} else if (Integer.parseInt(o.toString()) == R.drawable.nice_panda){
					//don't allow such things
				}
			}  
		});  
		//here we need to check to see if partner clicked it a pun
	}
}
